<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { getSpecialMenu, getCustomizeCategorize, getCustomizeMenu, addShopCar, addShopCarArray } from '@/api/shop'
	import { useUserStore } from '@/store/user'
	
	const user = useUserStore()
	const loading = ref(false)
	const navList = ref(['推荐套餐', '个性定制'])
	const navIndex = ref(0)
	const navTopList = ref([])
	const navTopCurrent = ref(-1)
	const navTopLeft = ref(0)
	const navLeftList = ref([])
	const navLeftCurrent = ref(-1)
	const goodsList = ref([])
	const customizeLoading = ref(false)
	const customizeLeftList = ref([])
	const customizeLeftCurrent = ref(-1)
	const customizeList = ref([])
	const customizePrice = ref(0)
	
	function handleNavIndex(index) {
		if(index != navIndex.value) {
			navIndex.value = index
			if(index == 0 && !navTopList.value.length) {
				getData()
			} else if(index == 1 && !customizeLeftList.value.length) {
				getCategorize()
			}
		}
	}
	function handleNavTop(index) {
		if(index != navTopCurrent.value) {
			navTopCurrent.value = index
			navTopLeft.value = index > 0 ? (index - 1) * 90 : 0
			let leftArr = navTopList.value[index].dishesSetGroups || []
			navLeftList.value = leftArr
			if(leftArr.length) handleNavLeft(0)
			else goodsList.value = []
		}
	}
	function handleNavLeft(index) {
		navLeftCurrent.value = index
		let goodsArr = navLeftList.value[index].dishesList || []
		goodsArr.forEach(item => {
			if(!item.num) {
				item.num = 0
				item.showAdd = true
			}
		})
		goodsList.value = goodsArr
	}
	function numChange() {
		let curNavLeft = navLeftList.value[navLeftCurrent.value]
		let maxNum = curNavLeft.requiredNum
		let curTotal = goodsList.value.reduce((total, item) => {
			total += item.num
			return total
		}, 0)
		if(curTotal >= maxNum) goodsList.value.forEach(item => item.showAdd = item.num? true : false)
		else goodsList.value.forEach(item => item.showAdd = true)
	}
	function addCar() {
		if(loading.value || navTopCurrent.value === -1) return
		let curNavTop = navTopList.value[navTopCurrent.value]
		let leftArr = curNavTop.dishesSetGroups || []
		const result = dealChildren(leftArr)
		if(!result.check) return
		loading.value = true
		let items = result.children.map(item => {
			return {
				goodsId: item.id,
				num: 1
			}
		})
		let data = {
			goodsId: curNavTop.setId,
			type: 'DISHES',
			num: 1,
			items
		}
		addShopCar(data).then(res => {
			uni.showToast({icon: 'success', title: '添加成功'})
			user.shopCarAction(false)
			clearCurData()
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function goBuy() {
		if(loading.value || navTopCurrent.value === -1) return
		let curNavTop = navTopList.value[navTopCurrent.value]
		let leftArr = curNavTop.dishesSetGroups || []
		const result = dealChildren(leftArr)
		if(!result.check) return
		loading.value = true
		let data = {
			total: curNavTop.price,
			list: [{
				id: curNavTop.setId,
				name: curNavTop.setName,
				furl: curNavTop.images && curNavTop.images[0] && curNavTop.images[0].furl || '',
				price: curNavTop.price,
				specs: curNavTop.specs,
				number: 1,
				type: 'DISHES',
				children: result.children
			}]
		}
		uni.navigateTo({
			url: '/pages/shop/orderConfirm',
			success: res => {
				res.eventChannel.emit('orderConfirm', data)
			}
		})
		loading.value = false
	}
	function dealChildren(leftArr = []) {
		let children = []
		if(!leftArr.length) {
			uni.showToast({
				icon: 'none',
				title: '请选择菜品'
			})
			return {children, check: false}
		}
		for(let i = 0; i < leftArr.length; i ++) {
			const item = leftArr[i]
			const maxNum = item.requiredNum
			let curTotal = 0
			let goodsArr = item.dishesList || []
			goodsArr.forEach(goods => {
				if(goods.num) {
					children.push({
						id: goods.dishesId,
						name: goods.dishesName,
						furl: goods.images && goods.images[0] && goods.images[0].furl || '',
						price: goods.price,
						specs: goods.specs,
						number: goods.num
					})
					curTotal += goods.num
				}
			})
			if(maxNum != curTotal) {
				let name = item.groupName || '-'
				let distance = maxNum - curTotal
				let title = `${name}还差${distance}道`
				if(distance < 0) title = `${name}多了${Math.abs(distance)}道`
				uni.showToast({
					icon: 'none',
					title
				})
				return {children, check: false}
			}
		}
		return {children, check: true}
	}
	function goCar() {
		uni.switchTab({url: '/pages/tabbar/shop'})
	}
	function getData() {
		loading.value = true
		getSpecialMenu({areaId: user.addressIds[2], status: 1}).then(res => {
			let result = res.result || []
			navTopList.value = result
			if(result.length) handleNavTop(0)
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function clearCurData() {
		let curNavTop = navTopList.value[navTopCurrent.value]
		let leftArr = curNavTop.dishesSetGroups || []
		leftArr.forEach(item => {
			let goodsArr = item.dishesList || []
			goodsArr.forEach(goods => {
				goods.num = 0
				goods.showAdd = true
			})
		})
	}
	function handleCustomizeLeft(index) {
		if(index != customizeLeftCurrent.value) {
			customizeLeftCurrent.value = index
			let curLeft = customizeLeftList.value[index]
			if(curLeft.dishesList && curLeft.dishesList.length) {
				customizeList.value = curLeft.dishesList
			} else {
				let typeId = curLeft.typeId
				curLeft.dishesList = []
				getCustomizeData(typeId, index)
			}
		}
	}
	function numCustomizeChange() {
		const goodsList = dealCustomizeList()
		let total = goodsList.reduce((total, item) => {
			total += item.number * 1000 * item.price
			return total
		}, 0)
		customizePrice.value = total / 1000
	}
	function addCustomizeCar() {
		if(customizeLoading.value) return
		const goodsList = dealCustomizeList()
		if(!goodsList.length) {
			uni.showToast({icon: 'none', title: '请选择菜品'})
			return
		}
		customizeLoading.value = true
		let data = goodsList.map(item => {
			return {
				goodsId: item.id,
				type: item.type,
				num: item.number
			}
		})
		addShopCarArray(data).then(res => {
			uni.showToast({icon: 'success', title: '添加成功'})
			user.shopCarAction(false)
			clearCustomizeCurData()
			customizeLoading.value = false
		}).catch(() => customizeLoading.value = false)
	}
	function goCustomizeBuy() {
		if(customizeLoading.value) return
		const goodsList = dealCustomizeList()
		if(!goodsList.length) {
			uni.showToast({icon: 'none', title: '请选择菜品'})
			return
		}
		customizeLoading.value = true
		let data = {
			total: customizePrice.value,
			list: goodsList
		}
		uni.navigateTo({
			url: '/pages/shop/orderConfirm',
			success: res => {
				res.eventChannel.emit('orderConfirm', data)
			}
		})
		customizeLoading.value = false
	}
	function dealCustomizeList() {
		let children = []
		customizeLeftList.value.forEach(item => {
			let goodsArr = item.dishesList || []
			goodsArr.forEach(goods => {
				if(goods.num) {
					children.push({
						id: goods.dishesId,
						name: goods.dishesName,
						furl: goods.images && goods.images[0] && goods.images[0].furl || '',
						price: goods.price,
						number: goods.num,
						type: 'DISHES_DIY',
					})
				}
			})
		})
		return children
	}
	function getCategorize() {
		customizeLoading.value = true
		getCustomizeCategorize().then(res => {
			let result = res.result || []
			customizeLeftList.value = result
			if(result.length) handleCustomizeLeft(0)
			customizeLoading.value = false
		}).catch(() => customizeLoading.value = false)
	}
	function getCustomizeData(typeId, index) {
		if(!typeId) return
		getCustomizeMenu({typeId, areaId: user.addressIds[2], status: 1}).then(res => {
			let result = res.result || []
			result.forEach(item => {
				if(!item.num) item.num = 0
			})
			let curLeft = customizeLeftList.value[index]
			curLeft.dishesList = result
			customizeList.value = curLeft.dishesList
		})
	}
	function clearCustomizeCurData() {
		customizeLeftList.value.forEach(item => {
			let goodsArr = item.dishesList || []
			goodsArr.forEach(goods => {
				food.num = 0
			})
		})
	}
	
	onLoad(() => {
		getData()
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head">
			<view :class="['head-item', navIndex == index? 'active' : '']" v-for="(nav, index) in navList" :key="nav" @click="handleNavIndex(index)">{{nav}}</view>
		</view>
		<view class="app-content">
			<template v-if="navIndex === 0">
				<scroll-view scroll-x="true" class="suggest-head" :scroll-left="navTopLeft" scroll-with-animation='true' v-if="navTopList.length">
					<view :class="['head-item', navTopCurrent == index? 'active' : '']" v-for="(nav, index) in navTopList" :key="nav.setId" 
						@click="handleNavTop(index)">
						<view class="head-box">
							<view class="head-image"><uv-image :src="nav.images && nav.images[0] && nav.images[0].furl" width="100%" height="100%"></uv-image></view>
							<view class="head-title uv-line-1">{{nav.setName}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="content-content">
					<scroll-view scroll-y="true" class="content-left" v-if="navLeftList.length">
						<view :class="['left-item', navLeftCurrent == index? 'active' : '']" v-for="(nav, index) in navLeftList" :key="nav.groupId"
							@click="handleNavLeft(index)">
							<view class="left-title">{{nav.groupName}}</view>
							<view class="left-des">(限选{{nav.requiredNum}}道)</view>
						</view>
					</scroll-view>
					<scroll-view scroll-y="true" class="content-right">
						<view class="right-box" v-if="goodsList.length">
							<view class="right-list">
								<view v-for="item in goodsList" :key="item.dishesId" class="good-box">
									<goods v-model="item.num" :img="item.images?.[0]?.furl" :name="item.dishesName" :price="item.price" 
										:specs="item.specification" :showAdd="item.showAdd" :max="1" @change="numChange"></goods>
								</view>
							</view>
						</view>
						<empty text="没有找到对应的套餐" v-else></empty>
					</scroll-view>
				</view>
				<view class="content-bottom" v-if="navTopList.length">
					<shopBar :carNum="user.shopCar.length" :totalPrice="navTopList[navTopCurrent]? navTopList[navTopCurrent].price : 0" 
						:loading="loading || navTopCurrent === -1" @car="goCar" @add="addCar" @buy="goBuy"></shopBar>
				</view>
			</template>
			<template v-else>
				<view class="content-content customize-content">
					<scroll-view scroll-y="true" class="content-left" v-if="customizeLeftList.length">
						<view :class="['left-item', customizeLeftCurrent == index? 'active' : '']" v-for="(nav, index) in customizeLeftList" :key="nav.typeId"
							@click="handleCustomizeLeft(index)">
							<view class="left-title">{{nav.typeName}}</view>
						</view>
					</scroll-view>
					<scroll-view scroll-y="true" class="content-right">
						<view class="right-box" v-if="customizeList.length">
							<view class="right-list">
								<view v-for="item in customizeList" :key="item.dishesId" class="good-box">
									<goods v-model="item.num" :img="item.images?.[0]?.furl" :name="item.dishesName" :price="item.price"
										:specs="item.specification" @change="numCustomizeChange"></goods>
								</view>
							</view>
						</view>
						<empty text="没有找到对应的菜品" v-else></empty>
					</scroll-view>
				</view>
				<view class="content-bottom" v-if="customizeLeftList.length">
					<shopBar :carNum="user.shopCar.length" :totalPrice="customizePrice" :loading="customizeLoading" @car="goCar" @add="addCustomizeCar"
						@buy="goCustomizeBuy"></shopBar>
				</view>
			</template>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		padding-top: 2rpx;
		height: 100vh;
		.app-head{
			width: 100%;
			height: 132rpx;
			padding: 24rpx;
			background-color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 24rpx;
			.head-item{
				flex: 1;
				height: 84rpx;
				line-height: 84rpx;
				border-radius: 8rpx;
				color: #525252;
				background-color: #FAF7F7;
				text-align: center;
				&.active{	
					font-weight: 600;
					color: #FD1024;
					background-color: #FFF4F2;
				}
			}
		}
		.app-content{
			padding-top: 16rpx;
			width: 100%;
			height: calc(100% - 134rpx);
		}
	}
	.suggest-head{
		width: 100%;
		height: 196rpx;
		white-space: nowrap;
		background-color: #FFFFFF;
		.head-item{
			display: inline-block;
			width: 172rpx;
			height: 100%;
			padding: 22rpx 0;
			.head-box{
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				.head-image{
					width: 104rpx;
					height: 104rpx;
					border-radius: 36rpx;
					border: 4rpx solid transparent;
					overflow: hidden;
				}
				.head-title{
					padding: 0 8rpx;
					border-radius: 36rpx;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
			}
			&.active{
				.head-image{
					border-color: rgba(250,63,0,0.8);
				}	
				.head-title{
					font-weight: 600;
					color: #FFFFFF;
					background-color: #FA3F00;
				}
			}
		}
		.head-item + .head-item{
			margin-left: 20rpx;
		}
	}
	.content-content{
		height: calc(100% - 308rpx);
		display: flex;
		&.customize-content{
			height: calc(100% - 112rpx);
			.content-left .left-item{
				padding: 32rpx 16rpx;
			}
		}
		.content-left{
			flex-shrink: 0;
			width: 180rpx;
			height: 100%;
			.left-item{
				display: flex;
				flex-direction: column;
				gap: 8rpx;
				padding: 16rpx;
				border-bottom: 2rpx solid #FFFFFF;
				text-align: center;
				position: relative;
				font-size: var(--theme-sm);
				line-height: var(--theme-sm-line);
				.left-title{
					font-weight: 600;
					color: #666666;
				}
				.left-des{
					color: #767473;
				}
				&.active{
					background-color: #FFF4F2;
					.left-title{
						color: #FD1024;
					}
					.left-des{
						color: #FD1024;
					}
					&::before{
						content: '';
						position: absolute;
						left: 0rpx;
						top: 0rpx;
						bottom: 0rpx;
						width: 6rpx;
						background-color: #FA3F00;
						z-index: 10;
					}
				}
			}
		}
		.content-right{
			flex: 1;
			height: 100%;
			background-color: #FFFFFF;
			.right-box{
				padding: 0 16rpx;
			}
			.right-list{
				width: 100%;
				background-color: #F4F4F4;
				display: flex;
				flex-direction: column;
				gap: 2rpx;
				.good-box{
					background-color: #FFFFFF;
					padding: 16rpx 0;
				}
			}
		}
	}
	.content-bottom{
		border-top: 1rpx solid #D7DBE1;
		height: 112rpx;
	}
</style>